package com.treeliked.udpdemo.util;

import com.treeliked.udpdemo.model.Message;

import java.io.*;

/**
 * msg 工具类
 *
 * @author lss
 * @date 2019-01-03, Thu
 */
public class MessageUtils {

    /**
     * 将消息对象转为字节数组
     *
     * @param msg 消息对象
     * @return 字节数组
     */
    public static byte[] messageToBytes(Message msg) {
        ByteArrayOutputStream baops = new ByteArrayOutputStream();
        ObjectOutputStream oops = null;
        try {
            oops = new ObjectOutputStream(baops);
            oops.writeObject(msg);
            oops.flush();
            return baops.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert oops != null;
                oops.close();
                baops.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 将字节数组转为message对象
     *
     * @param bytes 字节数组
     * @return 消息
     */
    public static Message bytesToMessage(byte[] bytes) {
        ByteArrayInputStream baips = new ByteArrayInputStream(bytes);
        ObjectInputStream oips = null;
        try {
            oips = new ObjectInputStream(baips);
            return (Message) oips.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                assert oips != null;
                oips.close();
                baips.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
